package com.atguigu.spring.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;


@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {
	
	@Autowired
	JdbcTemplate jdbcTemplate ;
	
	//根据书号获取书的单价
	@Override
	public int findBookPriceByIsbn(String isbn) {
		String querySql = "select price from book where isbn=?";
		int price = jdbcTemplate.queryForObject(querySql, Integer.class, isbn);
		return price;
	}

	//更新书的库存，使书号对应的库存 -1
	@Override
	public void updateBookStock(String isbn) {
		
		String querySql = "select stock from book_stock where isbn=?";
		int count = jdbcTemplate.queryForObject(querySql, Integer.class, isbn);
		if(count == 0){
			throw new BookStockException("图书库存不足！");
		}
		String updateSql = "update book_stock s set s.stock = s.stock - 1 where isbn=?";
		jdbcTemplate.update(updateSql, isbn);
	}

	//更新用户的账户余额： 使username 的balance - price
	@Override
	public void updateUserAccount(String username, int price) {
		String querySql = "select balance from account a where  a.username=? ";
		int balance = jdbcTemplate.queryForObject(querySql, Integer.class, username);
		if(balance < price){
			throw new UserAccountException("用户余额不足！");
		}
		
		String updateAccountSql = "update account a set a.balance=a.balance-? where  a.username=? ";
		jdbcTemplate.update(updateAccountSql, price, username);
	}

}
